<script setup lang="ts">
import { onMounted, watch } from 'vue'
import { menuRouters } from '../menu-routers'
import { useRoute } from 'vue-router'
import { useMainStore } from '@/store/main'
import { ArrowRight } from '@element-plus/icons-vue'

const route = useRoute()
const store = useMainStore()

onMounted(() => {
  // 设置面包屑
  setBreadcrumb()
})

/* 设置面包屑 */
const setBreadcrumb = () => {
  let breadData = [...store.$state.breadData]
  // 判断当前路由的meta是否为对象，如果为对象则取title作为路由名称
  const name = (Object.prototype.toString.call(route.meta) === '[object Object]'
    ? route.meta.title
    : route.meta) as unknown as string
  // 判断是否为菜单路由
  if (menuRouters.includes(route.path)) {
    breadData = [{ name, path: route.path }]
  } else {
    // 判断是否存在数组
    const index = breadData.findIndex((el) => {
      return el.path === route.path
    })
    // 确定为返回路由
    if (index >= 0) {
      breadData = breadData.slice(0, index + 1)
    } else {
      // 新增
      breadData.push({
        name,
        path: route.path,
      })
    }
  }
  store.saveBreadData(breadData)
}
/* 修改最后一个面包屑的name */
const updateTitle = (title: string) => {
  let breadData = [...store.$state.breadData]
  breadData[breadData.length - 1].name = title
  store.saveBreadData(breadData)
}

watch(
  () => route.path,
  () => {
    setBreadcrumb()
  },
  { deep: true },
)
defineExpose({ updateTitle })
</script>
<template>
  <div class="breadcrumb">
    <img class="tb" src="~@/assets/images/map-icon.png" alt="" />
    <span class="address">当前位置：</span>
    <el-breadcrumb class="swx-breadcrumb" :separator-icon="ArrowRight">
      <el-breadcrumb-item
        v-for="item in store.$state.breadData"
        :key="item.path"
        :to="{ path: item.path }"
      >
        {{ item.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<style lang="scss" scoped>
.breadcrumb {
  width: 100%;
  height: 30px;
  .tb {
    float: left;
  }
  .address {
    color: #879bba;
    font-size: 14px;
    float: left;
    margin: 0 8px;
  }
  .swx-breadcrumb {
    display: inline-block;
  }
  :deep(.el-breadcrumb) {
    line-height: normal;
  }
}
</style>
